﻿<%@ WebHandler Language="C#" Class="CommunityMgr" %>

using System;
using System.Web;
using System.Data;
using Chenxin.Lib.Utility;
using System.Collections.Generic;

/// <summary>
/// CommunityMgr Ajax服务页
/// 
/// 创建人：    熊世宏
/// 创建日期：  2010-04-12
/// </summary>
public class CommunityMgr : AjaxHandlerBase
{
    private static string Tname;
    private static string Tpy;
    public CommunityMgr()
    {
        htTypePermit.Add("add", Constants.Permit_CommunityInfoAdd);
        htTypePermit.Add("del", Constants.Permit_CommunityInfoDel);
        htTypePermit.Add("logicdel", Constants.Permit_CommunityInfoLogicDel);
        htTypePermit.Add("lock", Constants.Permit_CommunityInfoLock);
        htTypePermit.Add("unlock", Constants.Permit_CommunityInfoUnLock);
        htTypePermit.Add("edit", Constants.Permit_CommunityInfoEdit);
        htTypePermit.Add("exportdata", Constants.Permit_CommunityInfoExport);
        htTypePermit.Add("logicdelbuildingname", Constants.Permit_CommunityInfoLogicDel);
    }
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        if (context.Request["op"] != null)
        {
            switch (context.Request["op"].ToLower())
            {
                case "add":
                    Add(context);
                    break;
                case "edit":
                    Edit(context);
                    break;
                case "del":
                    Del(context);
                    break;
                case "getlist":
                    GetList(context);
                    break;
                case "getmodel":
                    GetModel(context);
                    break;
                case "validate_community":  //小区名称验证并返回拼音缩写
                    VCommunity(context);
                    break;
                case "validate_address":        //主要地址验证
                    VAddress(context);
                    break;
                case "validate":
                    Validate(context);
                    break;
                case "bulkadd":
                    BulkAdd(context);
                    break;
                case "logicdel":
                    LogicDel(context);
                    break;
                case "lock":
                    Lock(context);
                    break;
                case "unlock":
                    UnLock(context);
                    break;
                case "clearcach":
                    ClearCach(context);
                    break;
                case "logicdelbuildingname":
                    logicDelBuildingName(context);
                    break;
                case "clearbuildingcache":
                    ClearBuildingCache(context);
                    break;
                case "checkneedarea":
                    CheckNeedArea(context);
                    break;
                default:
                    break;
            }
        }
    }

    /// <summary>
    /// 检查是否需要选择片区
    /// </summary>
    /// <param name="context"></param>
    private void CheckNeedArea(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.BLL.BlockSetting setting = new Chenxin.Lib.House.BLL.BlockSetting();
            context.Response.Write("{success:1,msg:'',data:{needArea:" + setting.CheckBlockRole(new Guid(context.Request["companyid"])).ToString().ToLower() + "}}");
        }
        catch(Exception e)
        {
            context.Response.Write("{success:0,msg:'获取失败！',data:''}");
        }
    }

    /// <summary>
    /// 批量删除楼栋
    /// </summary>
    /// <param name="context"></param>
    private void logicDelBuildingName(HttpContext context)
    {
        try
        {
            string[] modelidArry = context.Request["idList"].Split(',');
            for (int i = 0; i < modelidArry.Length; i++)
            {
                Chenxin.Lib.House.Entity.Community_BuildingInfo model = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(modelidArry[i]));
                if (model != null)
                {
                    Chenxin.Lib.House.DAL.Community_BuildingInfo.UpdateStatus(model.BuildingId, -1);
                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId + "_1_50");
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    cs.Delete(string.Format(strCachKey));

                    //操作日志
                    AddLog(string.Format("{0}，工号：{1}，在{2}时逻辑删除了{3}小区{4}的楼栋",CurrentUserInfo.UserName,CurrentUserInfo.UserCode,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),model.CommunityId, model.BuildingName), "楼栋逻辑删除");
                }
            }
            context.Response.Write("{success:'1',msg:'逻辑删除成功！',data:''}");
        }
        catch (Exception e)
        {
            context.Response.Write("{success:1,msg:'缓存清除失败！原因：" + e.Message + "',data:''}");
        }
    }

    private void ClearBuildingCache(HttpContext context)
    {
        try
        {
            string  id = context.Request["idList"];
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, id + "_1_50");
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(string.Format(strCachKey));

            //操作日志
            AddLog(string.Format("{0}，工号：{1}，在{2}清除了记录为{3}的楼栋缓存", CurrentUserInfo.UserName,CurrentUserInfo.UserCode,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), id), "楼栋缓存清除");
            
            context.Response.Write("{success:1,msg:'缓存清除成功！',data:''}");
        }
        catch (Exception e)
        {
            context.Response.Write("{success:1,msg:'缓存清除失败！原因：" + e.Message + "',data:''}");
        }
    }
    
    private void ClearCach(HttpContext context)
    {
        try
        {
            string[] modelidArry = context.Request["idList"].Split(',');
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);

            for (int i = 0; i < modelidArry.Length; i++)
            {
                //删除小区本身Model缓存
                cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYINFO, modelidArry[i]));
                //删除下拉框缓存
                cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, modelidArry[i]));
            }

            //删除楼栋缓存
            DataTable dt = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetList(string.Format("CommunityId in ('{0}')", context.Request["idList"].Replace(",", "','")), "BuildingId");
            foreach (DataRow dr in dt.Rows)
            {
                cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, dr.ItemArray[0]));
            }

            //删除房源缓存
            dt = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(string.Format("CommunityId in ('{0}')", context.Request["idList"].Replace(",", "','"))).Tables[0];

            Chenxin.Lib.Cache.CacheService csg = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            foreach (DataRow dr in dt.Rows)
            {
                csg.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, dr["HouseId"]));
            }
            
            //删除房源缓存

            //操作日志
            AddLog(string.Format("{0}，工号：{1}，在{2}清除了记录为{3}的楼盘缓存", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["idList"].Split(',')), "楼盘缓存清除");
            context.Response.Write("{success:1,msg:'缓存清除成功！',data:''}");
        }
        catch(Exception e)
        {
            context.Response.Write("{success:1,msg:'缓存清除失败！原因：" + e.Message + "',data:''}");      
        }


    }

    /// <summary>
    /// 批量添加
    /// </summary>
    /// <param name="context"></param>
    private void BulkAdd(HttpContext context)
    {
        try
        {
            if (context.Request["model"] != null)
            {
                Chenxin.Lib.House.Entity.Community_BaseInfo model = (Chenxin.Lib.House.Entity.Community_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BaseInfo));

                model.AddTime = DateTime.Now;
                model.AddPerson = CurrentUserInfo.UserName;
                model.Status = 1;

                int count = 0;
                string nameList = "";           //用于添加的楼盘名称列表，用,分割
                string existNameList = GetAllNameList(model.CityId);//当前城市所有楼盘名称列表，用,分割
                string addressList = "";
                int maxNum = 0;
                int minNum = 0;
                int step = 1;
                if (context.Request["step"] != null)
                {
                    step = Convert.ToInt32(context.Request["step"]);
                }
                if (context.Request["setting"] == "number")
                {
                    maxNum = Convert.ToInt32(context.Request["MaxNumber"]) > Convert.ToInt32(context.Request["MinNumber"]) ? Convert.ToInt32(context.Request["MaxNumber"]) : Convert.ToInt32(context.Request["MinNumber"]);
                    minNum = Convert.ToInt32(context.Request["MaxNumber"]) < Convert.ToInt32(context.Request["MinNumber"]) ? Convert.ToInt32(context.Request["MaxNumber"]) : Convert.ToInt32(context.Request["MinNumber"]);

                    for (int i = minNum; i <= maxNum; i += step)
                    {
                        string format = "";
                        int length = Convert.ToInt32(context.Request["LengthNumber"]);
                        while (length > 0)
                        {
                            format += "0";
                            length--;
                        }

                        string _name = model.CommunityName.Replace("(*)", string.Format(string.Format("{{0:{0}}}", format), i)) + ",";
                        if (existNameList.IndexOf("," + _name) == -1)
                        {
                            nameList += _name;
                            addressList += model.Address.Replace("(*)", string.Format(string.Format("{{0:{0}}}", format), i)) + ",";
                        }
                    }
                }
                else
                {
                    maxNum = Convert.ToInt32(context.Request["MaxChar"][0]) > Convert.ToInt32(context.Request["MinChar"][0]) ? Convert.ToInt32(context.Request["MaxChar"][0]) : Convert.ToInt32(context.Request["MinChar"][0]);
                    minNum = Convert.ToInt32(context.Request["MaxChar"][0]) < Convert.ToInt32(context.Request["MinChar"][0]) ? Convert.ToInt32(context.Request["MaxChar"][0]) : Convert.ToInt32(context.Request["MinChar"][0]);

                    for (int i = minNum; i <= maxNum; i += step)
                    {
                        string _name = model.CommunityName.Replace("(*)", (char)i+"") + ",";
                        if (existNameList.IndexOf("," + _name) == -1)
                        {
                            nameList += _name;
                            addressList += model.Address.Replace("(*)", string.Format(string.Format("{{0:{0}}}", (char)i + ""), i)) + ",";
                        }
                    }
                }

                //string[] addressArry=n
                string[] nameArray = nameList.Split(',');
                string[] addressArray=addressList.Split(',');
                string nameTemp = "";
                for (int i = 0; i < nameArray.Length; i++)
                {
                    if (nameArray[i] != "")
                    {
                        model.CommunityName = nameArray[i];
                        model.Address = addressArray[i];
                        model.PY = Chenxin.Lib.Utility.InitialHelper.GetChineseSpell(model.CommunityName);
                        model.CommunityId = System.Guid.NewGuid();
                        nameTemp += nameArray[i] + "，";

                        Chenxin.Lib.House.DAL.Community_BaseInfo.Add(model);
                        count++;
                    }
                }

                if (count > 0)
                {
                    if (count == nameList.Split(',').Length - 1)
                    {
                        context.Response.Write("{success:'1',msg:'全部批量添加成功！',data:''}");
                    }
                    else
                    {
                        context.Response.Write("{success:'1',msg:'部分添加成功！" + nameTemp + "',data:''}");
                    }

                    //添加用户操作日志 2010-5-12 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "批量添加了一些楼盘",
                            OperationType.OperationTypeComboList()["OprType_CommunityBuildingAdd"].ToString());
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'批量添加失败！所需要添加的楼栋已经存在',data:''}");
                }

            }
        }
        catch (Exception e)
        {
            context.Response.Write("{success:'0',msg:'批量添加失败！原因：" + e.Message + "',data:''}");
        }
    }

    /// <summary>
    /// 获取需要插入的名称字符串，用于批量添加，排除已经插入过的楼栋
    /// </summary>
    /// <param name="communityId"></param>
    /// <param name="nameList"></param>
    /// <returns></returns>
    private string GetAllNameList(Guid cityId)
    {
        DataTable dt = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(string.Format(" CityId='{0}'  and Status<>1", cityId)).Tables[0];

        string tempList="";
        foreach (DataRow dr in dt.Rows)
        {
            tempList += dr["CommunityName"].ToString() + ",";

        }
        if (tempList.Length > 1)
        {
            tempList = "'" + tempList;
        }
        return tempList;
    }

    private void VCommunity(HttpContext context)
    {
        string op = context.Request["submitop"];
        string strWhere = string.Format(" CommunityName='{0}' and Status<>-1 ", context.Request["name"]);
        if (op == "edit")
            strWhere += string.Format(" and CommunityId<>'{0}' ", context.Request["modelid"]);
        string py = string.Empty;
        if (context.Request["name"] != Tname)
        {
            py = Chenxin.Lib.Utility.InitialHelper.GetChineseSpell(context.Request["name"]);
        }
        else
        {
            py = Tpy;
        }
        
        if (Chenxin.Lib.House.DAL.Community_BaseInfo.Exists(strWhere))
        {
            context.Response.Write("{success:'1',msg:'',data:{exist:false,py:'" + py + "'}}");
        }
        else
        {
            context.Response.Write("{success:'1',msg:'',data:{exist:true,py:'" + py + "'}}");
        }
    }

    private void VAddress(HttpContext context)
    {
        string op = context.Request["submitop"];
        string strWhere = string.Format(" Address='{0}' and Status<>-1 ", context.Request["name"]);
        if (op == "edit")
            strWhere += string.Format(" and CommunityId<>'{0}' ", context.Request["modelid"]);

        if (Chenxin.Lib.House.DAL.Community_BaseInfo.Exists(strWhere))
        {
            context.Response.Write("{success:'1',msg:'',data:{exist:false}}");
        }
        else
        {
            context.Response.Write("{success:'1',msg:'',data:{exist:true}}");
        }
    }

    /// <summary>
    /// 验证
    /// </summary>
    /// <param name="context"></param>
    private void Validate(HttpContext context)
    {
        if (context.Request["clientid"] != null && context.Request[context.Request["clientid"]] != null)
        {
            string columnName = "";
            string py = "";
            switch (context.Request["clientid"].ToLower())
            {
                case "txtcommunity":
                    columnName = "CommunityName";
                    break;
                case "txtaddress":
                    columnName = "Address";
                    break;
            }

            string msg = "";
            if (columnName == "Address")
            {
                string strWhere = string.Format(" Address='{0}' and Status<>-1", context.Request["txtaddress"]);
                if (Chenxin.Lib.House.DAL.Community_BaseInfo.Exists(strWhere))
                {
                    msg = "该地址已经存在！";
                    context.Response.Write("{success:'0',msg:'" + msg + "',data:''}");
                }
                else
                {
                    context.Response.Write("{success:'1',msg:'',data:{py:'" + py + "'}}");
                }
            }
            else
            {
                context.Response.Write("{success:'1',msg:'',data:{py:'" + py + "'}}");
            }
        }
        else
        {
            context.Response.Write("{success:'0',msg:'',data:''}");
        }
    }

    /// <summary>
    /// 逻辑删除
    /// </summary>
    /// <param name="context"></param>
    private void LogicDel(HttpContext context)
    {
        ChangeStatus(context, -1);      
    }
    /// <summary>
    /// 冻结
    /// </summary>
    /// <param name="context"></param>
    private void Lock(HttpContext context)
    {
        ChangeStatus(context, -10);
    }
    /// <summary>
    /// 激活
    /// </summary>
    /// <param name="context"></param>
    private void UnLock(HttpContext context)
    {
        ChangeStatus(context, 1);
    }
    /// <summary>
    /// 改变记录状态，用来处理：激活、冻结、逻辑删除
    /// </summary>
    /// <param name="context"></param>
    private void ChangeStatus(HttpContext context,int status)
    {
        string msg = "逻辑删除";
        if (status == 1)
        {
            msg = "激活";
        }
        else if (status == -10)
        {
            msg = "冻结";
        }
        try
        {
            if (context.Request["modelid"] != null && context.Request["checkhouse"] != null)
            {
                if (context.Request["checkhouse"] == "true")
                {
                    if (Chenxin.Lib.House.DAL.House_BaseInfo.Exists(string.Format("CommunityId='{0}' and Status>-10", context.Request["modelid"])))
                    {
                        context.Response.Write("{success:'1',msg:'" + msg + "失败！',data:{hasHouse:true}}");
                    }
                    else
                    {
                        Chenxin.Lib.House.DAL.Community_BaseInfo.UpdateStatus(new Guid(context.Request["modelid"]), status);
                        context.Response.Write("{success:'1',msg:'" + msg + "成功！',data:''}");


                        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYINFO, context.Request["modelid"]);
                        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                        cs.Delete(strCachKey);



                        //操作日志
                        AddLog(string.Format("{0}，工号：{1}，在{2}对楼盘{3}进行了{4}操作", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["modelid"], msg), "楼盘" + msg);
                        
                    }
                }
                else
                {
                    Chenxin.Lib.House.DAL.Community_BaseInfo.UpdateStatus(new Guid(context.Request["modelid"]), status);
                    context.Response.Write("{success:'1',msg:'" + msg + "成功！',data:''}");


                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYINFO, context.Request["modelid"]);
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                    cs.Delete(strCachKey);

                    //操作日志
                    AddLog(string.Format("{0}，工号：{1}，在{2}对楼盘{3}进行了{4}操作", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["modelid"], msg), "楼盘" + msg);
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'" + msg + "失败,请选择一条记录！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:'0',msg:'" + msg + "失败！',data:''}");
        }         
    }
    
    
    /// <summary>
    /// 删除楼栋
    /// </summary>
    /// <param name="context"></param>
    private void Del(HttpContext context)
    {
        try
        {
            if (!Chenxin.Lib.House.DAL.House_BaseInfo.Exists(string.Format(" CommunityId='{0}' and Status>-10", context.Request["modelid"])))//判断是否添加过房源，已经逻辑删除的视作删除
            {
                if (context.Request["modelid"] != null)
                {
                    Chenxin.Lib.House.DAL.Community_BaseInfo.DelCommunity(new Guid(context.Request["modelid"]));
                    context.Response.Write("{success:'1',msg:'删除成功！',data:''}");

                    //操作日志
                    AddLog(string.Format("{0}，工号：{1}，在{2}对楼盘{3}进行了删除操作", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["modelid"]), "楼盘删除");
                    
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'删除失败,请选择一条记录！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'该小区已经添加过房源记录，建议执行逻辑删除！',data:''}");                
            }
        }
        catch
        {
            context.Response.Write("{success:'1',msg:'删除失败！',data:''}");
        }
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="contentx"></param>
    public void Add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.Community_BaseInfo model = (Chenxin.Lib.House.Entity.Community_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BaseInfo));

            if (!Chenxin.Lib.House.DAL.Community_BaseInfo.Exists(string.Format("CityId='{0}' and CommunityName='{1}' and Status<>-1", model.CityId, model.CommunityName)))
            {
                if (model.PY.Trim() == "")
                {
                    model.PY = Chenxin.Lib.Utility.InitialHelper.GetChineseSpell(model.CommunityName);
                }

                model.CommunityName = model.CommunityName.Trim();
                model.AddTime = DateTime.Now;
                model.AddPerson = CurrentUserInfo.UserName;
                model.CommunityId = System.Guid.NewGuid();
                model.Status = 1;
                Chenxin.Lib.House.DAL.Community_BaseInfo.Add(model);

                //添加用户操作日志 2010-5-12 王玮 Add
                AddLog("" + CurrentUserInfo.UserName + "添加了一个楼盘:[" + model.CommunityName + "]",
                        OperationType.OperationTypeComboList()["OprType_CommunityAdd"].ToString());

                context.Response.Write("{success:'1',msg:'保存成功！',data:{CommunityId:'" + model.CommunityId + "'}}");
            }
            else
            {
                context.Response.Write("{success:'0',msg:'保存失败，楼盘名称重复，该楼盘已经存在！',data:''}");
            }
        }
        catch(Exception e)
        {
            context.Response.Write("{success:'0',msg:'保存失败！"+e.Message+"',data:''}");            
        }

    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="context"></param>
    public void Edit(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.Community_BaseInfo model = (Chenxin.Lib.House.Entity.Community_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BaseInfo));

            //更新房源的区域，板块，片区字段内容
            //UpdateHouseInfo(model);
            
            model.AddTime = DateTime.Now;
            model.AddPerson = CurrentUserInfo.UserName;
            //model.Status = 1;
            Chenxin.Lib.House.Entity.Community_BaseInfo tempModel = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(model.CommunityId);
            string strContext = string.Empty;
            strContext = "原小区名称：" + tempModel.CommunityName + "；";
            if (model.Synchronization)
            {
                strContext += "同步房源；";
            }
            if (tempModel.CommunityName != model.CommunityName && (tempModel.CommunityName != "" || model.CommunityName != null))
            {
                strContext += "楼盘名称由[" + ((string.IsNullOrEmpty(tempModel.CommunityName)) ? "空" : tempModel.CommunityName) + "]改为：" + ((string.IsNullOrEmpty(model.CommunityName)) ? "空" : model.CommunityName) + "；";
            }
            if (tempModel.PY != model.PY && (tempModel.PY != "" || model.PY != null)) 
            {
                strContext += "拼音由[" + ((string.IsNullOrEmpty(tempModel.PY)) ? "空" : tempModel.PY) + "]改为：" + ((string.IsNullOrEmpty(model.PY)) ? "空" : model.PY) + "；";
            }
            if (tempModel.CompleteYear != model.CompleteYear && (tempModel.CompleteYear.ToString() != "" || model.CompleteYear != null))
            {
                strContext += "建筑年代由[" + ((string.IsNullOrEmpty(tempModel.CompleteYear.ToString())) ? "空" : tempModel.CompleteYear.ToString()) + "]改为：" + ((string.IsNullOrEmpty(model.CompleteYear.ToString())) ? "空" : model.CompleteYear.ToString()) + "；";
            }
            if (tempModel.CityName != model.CityName && (tempModel.CityName != "" || model.CityName != null))
            {
                strContext += "城市由[" + ((string.IsNullOrEmpty(tempModel.CityName)) ? "空" : tempModel.CityName) + "]改为：" + ((string.IsNullOrEmpty(model.CityName)) ? "空" : model.CityName) + "；";
            }
            if (tempModel.CompanyName != model.CompanyName && (tempModel.CompanyName != "" || model.CompanyName != null))
            {
                strContext += "公司由[" + ((string.IsNullOrEmpty(tempModel.CompanyName)) ? "空" : tempModel.CompanyName) + "]改为：" + ((string.IsNullOrEmpty(model.CompanyName)) ? "空" : model.CompanyName) + "；";
            }
            if (tempModel.Region != model.Region && (tempModel.Region != "" || model.Region != null))
            {
                strContext += "区域由[" + ((string.IsNullOrEmpty(tempModel.Region)) ? "空" : tempModel.Region) + "]改为：" + ((string.IsNullOrEmpty(model.Region)) ? "空" : model.Region) + "；";
            }
            if (tempModel.Block != model.Block && (tempModel.Block != "" || model.Block != null))
            {
                strContext += "板块由[" + ((string.IsNullOrEmpty(tempModel.Block)) ? "空" : tempModel.Block) + "]改为：" + ((string.IsNullOrEmpty(model.Block)) ? "空" : model.Block) + "；";
            }
            if (tempModel.CommunityBlock != model.CommunityBlock && (tempModel.CommunityBlock != "" || model.CommunityBlock != null))
            {
                strContext += "片区由[" + ((string.IsNullOrEmpty(tempModel.CommunityBlock)) ? "空" : tempModel.CommunityBlock) + "]改为：" + ((string.IsNullOrEmpty(model.CommunityBlock)) ? "空" : model.CommunityBlock) + "；";
            }
            if (tempModel.CommunityUse != model.CommunityUse && (tempModel.CommunityUse != "" || model.CommunityUse != null))
            {
                strContext += "用途由[" + ((string.IsNullOrEmpty(tempModel.CommunityUse)) ? "空" : tempModel.CommunityUse) + "]改为：" + ((string.IsNullOrEmpty(model.CommunityUse)) ? "空" : model.CommunityUse) + "；";
            }
            if (tempModel.BuildingType != model.BuildingType && (tempModel.BuildingType != "" || model.BuildingType != null))
            {
                strContext += "类型由[" + ((string.IsNullOrEmpty(tempModel.BuildingType)) ? "空" : tempModel.BuildingType) + "]改为：" + ((string.IsNullOrEmpty(model.BuildingType)) ? "空" : model.BuildingType) + "；";
            }
            if (tempModel.Address != model.Address && (tempModel.Address != "" || model.Address != null))
            {
                strContext += "主要地址由[" + ((string.IsNullOrEmpty(tempModel.Address)) ? "空" : tempModel.Address)  + "]改为：" + ((string.IsNullOrEmpty(model.Address)) ? "空" : model.Address) + "；";
            }
            if (tempModel.Address2 != model.Address2 && (tempModel.Address2 != "" || model.Address2 != null))
            {
                strContext += "备用地址1由[" + ((string.IsNullOrEmpty(tempModel.Address2)) ? "空" : tempModel.Address2)  + "]改为：" + ((string.IsNullOrEmpty(model.Address2)) ? "空" : model.Address2) + "；";
            }
            if (tempModel.Address3 != model.Address3 && (tempModel.Address3 != "" || model.Address3 != null))
            {
                strContext += "备用地址2由[" + ((string.IsNullOrEmpty(tempModel.Address3)) ? "空" : tempModel.Address3) + "]改为：" + ((string.IsNullOrEmpty(model.Address3)) ? "空" : model.Address3) + "；";
            }
            if (tempModel.Address4 != model.Address4 && (tempModel.Address4 != "" || model.Address4 != null))
            {
                strContext += "备用地址3由[" + ((string.IsNullOrEmpty(tempModel.Address4)) ? "空" : tempModel.Address4)  + "]改为：" + ((string.IsNullOrEmpty(model.Address4)) ? "空" : model.Address4) + "；";
            }
            if (tempModel.Schools != model.Schools && (tempModel.Schools != "" || model.Schools != null))
            {
                strContext += "学校由[" +((string.IsNullOrEmpty(tempModel.Schools)) ? "空" : tempModel.Schools)  + "]改为：" + ((string.IsNullOrEmpty(model.Schools)) ? "空" : model.Schools) + "；";
            }
            if (tempModel.Parks != model.Parks && (tempModel.Parks != "" || model.Parks != null))
            {
                strContext += "公园由[" + ((string.IsNullOrEmpty(tempModel.Parks)) ? "空" : tempModel.Parks)  + "]改为：" + ((string.IsNullOrEmpty(model.Parks)) ? "空" : model.Parks) + "；";
            }
            if (tempModel.Traffics != model.Traffics && (tempModel.Traffics != "" || model.Traffics != null))
            {
                strContext += "交通由[" + ((string.IsNullOrEmpty(tempModel.Traffics)) ? "空" : tempModel.Traffics)  + "]改为：" + ((string.IsNullOrEmpty(model.Traffics)) ? "空" : model.Traffics) + "；";
            }
            if (tempModel.Description != model.Description && (tempModel.Description != "" || model.Description != null))
            {
                strContext += "房源描述由[" + ((string.IsNullOrEmpty(tempModel.Description)) ? "空" : tempModel.Description) + "]改为：" + ((string.IsNullOrEmpty(model.Description)) ? "空" : model.Description) + "；";
            }

            Chenxin.Lib.House.Entity.House_CommunityLogs hsComLogs = new Chenxin.Lib.House.Entity.House_CommunityLogs();
            hsComLogs.RecordId = Guid.NewGuid();
            hsComLogs.CityId = CurrentUserInfo.CityId;
            hsComLogs.CityName = CurrentUserInfo.CityName;
            hsComLogs.CompanyId = CurrentUserInfo.CompanyId;
            hsComLogs.CompanyName = CurrentUserInfo.CompanyName;
            hsComLogs.DepartId = CurrentUserInfo.DepartId;
            hsComLogs.DepartName = CurrentUserInfo.DepartName;
            hsComLogs.UserId = CurrentUserInfo.UserId;
            hsComLogs.UserName = CurrentUserInfo.UserName;
            hsComLogs.Addtime = DateTime.Now;
            hsComLogs.OprType = "小区楼盘";
            hsComLogs.OperationContext = strContext;
            
            Chenxin.Lib.House.DAL.Community_BaseInfo.Update(model);
            Chenxin.Lib.House.DAL.House_CommunityLogs.Add(hsComLogs);
            
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYINFO, model.CommunityId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            cs.Set(strCachKey, model, DateTime.Now.AddDays(1));

            if (model.Synchronization)
            {
                //删除房源缓存
                Chenxin.Lib.Cache.CacheService cs1 = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                
                string strWhere = " CommunityId='" + model.CommunityId + "' ";
                List<Chenxin.Lib.House.Entity.House_BaseInfo> lsHouse = Chenxin.Lib.House.DAL.House_BaseInfo.GetListArray(strWhere);
                if (lsHouse.Count >= 1)
                {
                    for(int i=0;i<lsHouse.Count;i++)
                    {
                        lsHouse[i].Address = model.Address;
                        lsHouse[i].CommunityId = model.CommunityId;
                        lsHouse[i].Community = model.CommunityName;
                        lsHouse[i].Region = model.Region;
                        lsHouse[i].Block = model.Block;
                        lsHouse[i].HouseBlock = model.CommunityBlock;
                        lsHouse[i].DetailAddress = model.Address + lsHouse[i].BuildingName + lsHouse[i].Room;
                        Chenxin.Lib.House.DAL.House_BaseInfo.Update(lsHouse[i]);

                        cs1.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, lsHouse[i].HouseId));
                    }
                }
            }
            
            //添加用户操作日志 2010-5-12 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "编辑了一个楼盘:[" + model.CommunityName + "]",
                    OperationType.OperationTypeComboList()["OprType_CommunityEdit"].ToString());

            context.Response.Write(("{success:'1',msg:'保存成功！',data:{CommunityId:'" + model.CommunityId + "'}}"));
        }
        catch(Exception e)
        {
            context.Response.Write(("{success:'0',msg:'保存失败，"+e.Message+"！',data:''}"));  
        }
    }

    /// <summary>
    /// 更新房源区域，板块，片区字段
    /// </summary>
    /// <param name="model"></param>
    public void UpdateHouseInfo(Chenxin.Lib.House.Entity.Community_BaseInfo model)
    {
        Chenxin.Lib.House.Entity.Community_BaseInfo oldModel = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(model.CommunityId);

        if (oldModel.Region != model.Region || oldModel.Block != model.Block || oldModel.CommunityBlock != model.CommunityBlock)
        {
            Chenxin.Lib.House.DAL.House_BaseInfo.UpdateHouseRBA(model.CommunityId, model.Region, model.Block, model.CommunityBlock);

            //删除房源缓存
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            DataTable dt = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(string.Format("CommunityId = '{0}'", model.CommunityId)).Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, dr["HouseId"]));
            }
        }        
    }
    
    /// <summary>
    /// 获取model
    /// </summary>
    /// <param name="context"></param>
    public void GetModel(HttpContext context)
    {
        try
        {
            Tname = null;
            Tpy = null;
            Chenxin.Lib.House.Entity.Community_BaseInfo model = null;
            
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYINFO, context.Request["modelid"]);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            model = cs.GetObject<Chenxin.Lib.House.Entity.Community_BaseInfo>(strCachKey);
            if (!cs.Hit)
            {
                model = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(new Guid(context.Request["modelid"]));
                if (model != null)
                {
                    cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
                }
            }


            if (model != null)
            {
                context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + "}}"));
                Tname = model.CommunityName;
                Tpy = model.PY;
                /*
                if (model.Status == 1 || model.Status == -10)
                {
                    context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + "}}"));
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'获取记录失败，该小区已经被删除！',data:''}");
                }
                 * */
            }
            else
            {
                context.Response.Write("{success:'0',msg:'获取记录信息失败！',data:''}");
            }
        }
        catch(Exception e)
        {
            context.Response.Write(("{success:'0',msg:'获取记录信息失败！"+e.Message+"',data:{model:{}}}"));              
        }
    }

    /// <summary>
    /// 重写
    /// </summary>
    /// <param name="columnName"></param>
    /// <param name="columnVal"></param>
    /// <param name="dr"></param>
    /// <returns></returns>
    public override string CustomerRowDefine(string columnName, string columnVal, DataRow dr)
    {
        if (columnName == "CommunityName")
        {
            return string.Format("<a href=\"CommunityInfo.aspx?id={0}\" title=\"{1}\" >{1}</a>", dr["CommunityId"], columnVal);
        }
        else if (columnName == "Status") {
            if (columnVal == "1")
            {
                return "<span style=\"color:#009900;\">正常</span>";
            }
            else if (columnVal == "-1")
            {
                return "<span style=\"color:#ff0000;\">已删除</span>";
            }
            else
            {
                return "<span style=\"color:#0000ff\">已冻结</span>";
            }
        }
        return columnVal;
    }

    //获取列表信息
    public void GetList(HttpContext context)
    {
        string strWhere = "1=1";
        string order = "AddTime desc,CommunityName desc";

        int pageSize = 10;
        int pageIndex = 1;
        int count = 0;

        if (context.Request["pagesize"] != null)
        {
            pageSize = Convert.ToInt32(context.Request["pagesize"]);
        }
        if (context.Request["pageindex"] != null)
        {
            pageIndex = Convert.ToInt32(context.Request["pageindex"])+1;
        }

        if (context.Request["communityname"] != null)
        {
            strWhere += string.Format(" and CommunityName like '%{0}%'", context.Request["communityname"]);
        }

        if (context.Request["region"] != null)
        {
            strWhere += string.Format(" and Region='{0}'", context.Request["region"]);
        }

        if (context.Request["cityid"] != null)
        {
            strWhere += string.Format(" and CityId='{0}'", context.Request["cityid"]);
        }
        else
        {
            strWhere += string.Format(" and CityId='{0}'", CurrentUserInfo.CityId);
        }

        if (context.Request["companyid"] != null)
        {
            strWhere += string.Format(" and CompanyId='{0}'", context.Request["companyid"]);
        }
        
        if (context.Request["block"] != null)
        {
            strWhere += string.Format(" and Block='{0}'", context.Request["block"]);
        }
        if (context.Request["Address"] != null)
        {
            strWhere += string.Format(" and Address like '%{0}%'", context.Request["address"]);
        }
        if (context.Request["status"] != null && context.Request["status"] != "")
        {
            strWhere += string.Format("and Status in ({0})", context.Request["status"]);
        }

        if (context.Request["sort"] != null&&context.Request["sort"]!="")
        {
            order = context.Request["sort"];
        }


        DataSet ds = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(pageIndex, pageSize, order, "Community_BaseInfo", strWhere, "*", "*", true);
        count = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);


        context.Response.Write(string.Format("{{success:'1',data:{{html:'{0}',count:{1}}}}}", CreateDlGrid(ds.Tables[0], context.Request["field"], "CommunityId"), count));
        
        //context.Response.Write(string.Format("{{success:'1',data:{{data:'{0}',count:{1}}}}}", CreateGrid(ds.Tables[0].Select("1=1")), count));
        
    }

    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        context.Response.ContentType = "text/plain";
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        string op = context.Request.Params["op"];

        if (String.IsNullOrEmpty(op))
        {
            strMsg = "{success:0,msg:'操作参数有误！',data:''}";
            return false;
        }
        op = op.ToLower();

        string code = context.Request.Params["code"];
        if (op.Equals("checkpermit"))
        {
            if (String.IsNullOrEmpty(code))
            {
                strMsg = "{success:0,msg:'权限检查参数有误！',data:''}";
                return false;
            }
            code = code.ToLower();
            //权限判断
            //传递参数用
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();

            //编辑关键字
            if (code.Equals("edit"))
            {
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_House_EditCommunityKey))
                {
                    strMsg = "{success:1,msg:'',data:{permit:{editall:true}}}";
                    return true;
                }
                else
                {
                    strMsg = "{success:1,msg:'',data:{permit:{editall:false}}}";
                    return true;
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
}